//
//  AppDelegate.m
//  MatchTouch
//
//  Created by SUN DONG LEE on 13. 1. 21..
//  Copyright (c) 2013년 SUN DONG LEE. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import <sqlite3.h>

@implementation AppDelegate

//@synthesize stages, highScores, highStars;
//@synthesize highWaterMark;

@synthesize highWaterMark = _highWaterMark;

- (void) setHighWaterMark:(int)highWaterMark {
    //self.highWaterMark = highWaterMark; //hides instance variable warning at this line
    _highWaterMark = highWaterMark;
    
    NSLog(@"save highWaterMark to DB: %d", _highWaterMark);
    [self saveHighWaterMarkToDB];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    _highWaterMark=1;
    _highScores = [[NSMutableDictionary alloc] init];
    _highStars = [[NSMutableDictionary alloc] init];
    _info = [[NSMutableDictionary alloc] init];
    
    
    [self fillData]; //NSArray에 stage별 문제 집어넣기
    [self createdb]; //document 디렉토리에 데이터베이스 파일이 존재하지 않으면 생성하고 score 테이블도 만듦. 이미 존재하면 기존것 이용.
    [self readdb];   //db를 읽어서 예전 결과값으로 초기화하기
    

    //[self soundPlayLoop:@"FILE_2012031555_1_124_Keeprunning.mp3"];
    [self soundPlayLoop:@"FILE_2012022951_1_117_Soundofmusic.mp3"];
    return YES;
}


- (void)fillData {
    
    _stages = [[NSMutableArray alloc] init];
    
    //stage1
    NSArray *oppTextArray1 = [[NSArray alloc] initWithObjects:
                              @"on",
                              @"up",
                              @"happy",
                              @"high",
                              @"yes",
                              @"short",
                              nil];
    
    NSArray *oppTextArray2 = [[NSArray alloc] initWithObjects:
                              @"off",
                              @"down",
                              @"sad",
                              @"low",
                              @"no",
                              @"long",
                              nil];
    
    NSArray *stage1 = [[NSArray alloc] initWithObjects:oppTextArray1, oppTextArray2, nil];
    [_stages addObject:stage1];
    


    
    
	//stage2
    NSArray *oppTextArray3 = [[NSArray alloc] initWithObjects:
                              @"in",                              
                              @"full",
                              @"above",
                              @"few",
                              @"new",
                              @"heavy",
                              nil];
    
    NSArray *oppTextArray4 = [[NSArray alloc] initWithObjects:
                              @"out",
                              @"empty",
                              @"below",
                              @"many",
                              @"old",
                              @"light",
                              nil];
    
    NSArray *stage2 = [[NSArray alloc] initWithObjects:oppTextArray3, oppTextArray4, nil];
    [_stages addObject:stage2];
    
    
	//stage3
    NSArray *oppTextArray5 = [[NSArray alloc] initWithObjects:
                              @"small",
                              @"shut",
                              @"front",
                              @"slow",
                              @"hot",
                              @"clean",
                              nil];
    
    NSArray *oppTextArray6 = [[NSArray alloc] initWithObjects:
                              @"big",
                              @"open",
                              @"back",
                              @"fast",
                              @"cold",
                              @"dirty",
                              nil];
    
    NSArray *stage3 = [[NSArray alloc] initWithObjects:oppTextArray5, oppTextArray6, nil];
    [_stages addObject:stage3];
    
    
    //stage4
    NSArray *oppTextArray7 = [[NSArray alloc] initWithObjects:
                              @"cheap",
                              @"deep",
                              @"easy",
                              @"far",
                              @"good",
                              @"here",
                              nil];
    
    NSArray *oppTextArray8 = [[NSArray alloc] initWithObjects:
                              @"expensive",
                              @"shallow",
                              @"difficult",
                              @"near",
                              @"bad",
                              @"there",
                              nil];

    NSArray *stage4 = [[NSArray alloc] initWithObjects:oppTextArray7, oppTextArray8, nil];
    [_stages addObject:stage4];
    
    
    //stage5
    NSArray *oppTextArray9 = [[NSArray alloc] initWithObjects:
                              @"thin",
                              @"inside",
                              @"rich",
                              @"right",
                              @"safe",
                              @"smooth",
                              nil];
    
    NSArray *oppTextArray10 = [[NSArray alloc] initWithObjects:
                               @"fat",
                               @"outside",
                               @"poor",
                               @"left",
                               @"dangerous",
                               @"rough",
                               nil];
                              
    NSArray *stage5 = [[NSArray alloc] initWithObjects:oppTextArray9, oppTextArray10, nil];
    [_stages addObject:stage5];
    

    //stage6
    NSArray *oppTextArray11 = [[NSArray alloc] initWithObjects:
                               @"strong",
                               @"tall",
                               @"tight",
                               @"wide",
                               @"young",
                               @"light",
                               nil];
                              
    NSArray *oppTextArray12 = [[NSArray alloc] initWithObjects:
                              @"weak",
                              @"short",
                              @"loose",
                              @"narrow",
                              @"old",
                              @"dark",
                              nil];
    
    NSArray *stage6 = [[NSArray alloc] initWithObjects:oppTextArray11, oppTextArray12, nil];
    [_stages addObject:stage6];
    
    
    //stage7    
    NSArray *oppTextArray13 = [[NSArray alloc] initWithObjects:
                               @"smile",
                               @"buy",
                               @"this",
                               @"never",
                               @"stop",
                               @"wrong",
                               nil];
    
    NSArray *oppTextArray14 = [[NSArray alloc] initWithObjects:
                               @"frown",
                               @"sell",
                               @"that",
                               @"always",
                               @"start",
                               @"right",
                               nil];
    
    NSArray *stage7 = [[NSArray alloc] initWithObjects:oppTextArray13, oppTextArray14, nil];
    [_stages addObject:stage7];
    
    
    //stage8
    NSArray *oppTextArray15 = [[NSArray alloc] initWithObjects:
                               @"love",
                               @"throw",
                               @"dry",
                               @"forward",
                               @"stand",
                               @"lost",
                               nil];
    
    NSArray *oppTextArray16 = [[NSArray alloc] initWithObjects:
                               @"hate",
                               @"catch",
                               @"wet",
                               @"backward",
                               @"sit",
                               @"found",
                               nil];
    
    NSArray *stage8 = [[NSArray alloc] initWithObjects:oppTextArray15, oppTextArray16, nil];
    [_stages addObject:stage8];
    
    
    
    //stage9
    NSArray *oppTextArray17 = [[NSArray alloc] initWithObjects:
                               @"hard",
                               @"day",
                               @"white",
                               @"intelligent",
                               @"shy",
                               @"success",
                               nil];
    
    NSArray *oppTextArray18 = [[NSArray alloc] initWithObjects:
                               @"soft",
                               @"night",
                               @"black",
                               @"stupid",
                               @"outgoing",
                               @"failure",
                               nil];
    
    NSArray *stage9 = [[NSArray alloc] initWithObjects:oppTextArray17, oppTextArray18, nil];
    [_stages addObject:stage9];
    

    //stage10
    NSArray *oppTextArray19 = [[NSArray alloc] initWithObjects:
                              @"care",
                              @"confess",
                              @"cool",
                              @"cruel",
                              @"early",
                              @"earn",
                               nil];
    
    NSArray *oppTextArray20 = [[NSArray alloc] initWithObjects:
                               @"neglect",
                               @"deny",
                               @"warm",
                               @"kind",
                               @"late",
                               @"spend",
                               nil];

    NSArray *stage10 = [[NSArray alloc] initWithObjects:oppTextArray19, oppTextArray20, nil];
    [_stages addObject:stage10];
    
    
    //stage11
    NSArray *oppTextArray21 = [[NSArray alloc] initWithObjects:
                               @"false",
                               @"guilty",
                               @"freedom",
                               @"foolish",
                               @"fresh",
                               @"fine",
                               nil];
    
    NSArray *oppTextArray22 = [[NSArray alloc] initWithObjects:
                               @"true",
                               @"innocent",
                               @"slavery",
                               @"wise",
                               @"stale",
                               @"coarse",
                               nil];

    NSArray *stage11 = [[NSArray alloc] initWithObjects:oppTextArray21, oppTextArray22, nil];
    [_stages addObject:stage11];
    
    
    //stage12
    NSArray *oppTextArray23 = [[NSArray alloc] initWithObjects:
                               @"civilized",
                               @"fear",
                               @"humble",
                               @"honour",
                               @"joy",
                               @"knowledge",
                               nil];
                              
    NSArray *oppTextArray24 = [[NSArray alloc] initWithObjects:
                              @"savage",
                              @"courage",
                              @"arrogant",
                              @"dishonour",
                              @"sorrow",
                              @"ignorance",
                              nil];
    
    NSArray *stage12 = [[NSArray alloc] initWithObjects:oppTextArray23, oppTextArray24, nil];
    [_stages addObject:stage12];
    
    
    //stage13
    NSArray *oppTextArray25 = [[NSArray alloc] initWithObjects:
                               @"lie",
                               @"masculine",
                               @"make",
                               @"noisy",
                               @"permanent",
                               @"presence",
                               nil];
    
    
    NSArray *oppTextArray26 = [[NSArray alloc] initWithObjects:
                               @"truth",
                               @"feminine",
                               @"mar",
                               @"quiet",
                               @"temporary",
                               @"absence",
                               nil];
    
    NSArray *stage13 = [[NSArray alloc] initWithObjects:oppTextArray25, oppTextArray26, nil];
    [_stages addObject:stage13];
    
    
    //stage14
    NSArray *oppTextArray27 = [[NSArray alloc] initWithObjects:
                               @"prose",
                               @"fast",
                               @"receive",
                               @"reject",
                               @"ripe",
                               @"remember",
                               nil];

    NSArray *oppTextArray28 = [[NSArray alloc] initWithObjects:
                               @"poetry",
                               @"slow",
                               @"give",
                               @"accept",
                               @"raw",
                               @"forget",
                               nil];
    
    NSArray *stage14 = [[NSArray alloc] initWithObjects:oppTextArray27, oppTextArray28, nil];
    [_stages addObject:stage14];
    
    
    //stage15
    NSArray *oppTextArray29 = [[NSArray alloc] initWithObjects:
                               @"tragedy",
                               @"general",
                               @"victory",
                               @"wild",
                               @"wisdom",
                               @"laugh",
                               nil];
          
    NSArray *oppTextArray30 = [[NSArray alloc] initWithObjects:
                               @"comedy",
                               @"particular",
                               @"defeat",
                               @"domestic",
                               @"folly",
                               @"cry",
                               nil];
    
    NSArray *stage15 = [[NSArray alloc] initWithObjects:oppTextArray29, oppTextArray30, nil];
    [_stages addObject:stage15];
    
    
    //stage16    
    NSArray *oppTextArray31 = [[NSArray alloc] initWithObjects:
                               @"import",
                               @"interior",
                               @"maximum",
                               @"include",
                               @"junior",
                               @"majority",
                               nil];
    
    NSArray *oppTextArray32 = [[NSArray alloc] initWithObjects:
                               @"export",
                               @"exterior",
                               @"minimum",
                               @"exclude",
                               @"senior",
                               @"minority",
                               nil];
    
    NSArray *stage16 = [[NSArray alloc] initWithObjects:oppTextArray31, oppTextArray32, nil];
    [_stages addObject:stage16];
    
    
    //stage17                               
    NSArray *oppTextArray33 = [[NSArray alloc] initWithObjects:
                               @"optimist",
                               @"superior",
                               @"accept",
                               @"acquire",
                               @"ancient",
                               @"agree",
                               nil];
    
    NSArray *oppTextArray34 = [[NSArray alloc] initWithObjects:
                               @"pessimist",
                               @"inferior",
                               @"refuse",
                               @"lose",
                               @"modern",
                               @"disagree",
                               nil];
    
    NSArray *stage17 = [[NSArray alloc] initWithObjects:oppTextArray33, oppTextArray34, nil];
    [_stages addObject:stage17];
    

    //stage18    
    NSArray *oppTextArray35 = [[NSArray alloc] initWithObjects:
                               @"alive",
                               @"barren",
                               @"admire",
                               @"blunt",
                               @"bold",
                               @"broad",
                               nil];
    
    NSArray *oppTextArray36 = [[NSArray alloc] initWithObjects:
                               @"dead",
                               @"fertile",
                               @"despise",
                               @"sharp",
                               @"timid",
                               @"narrow",
                               nil];
    
    NSArray *stage18 = [[NSArray alloc] initWithObjects:oppTextArray35, oppTextArray36, nil];
    [_stages addObject:stage18];

}

AVAudioPlayer *av;
NSString *sndPath;

AVAudioPlayer *av2;
NSString *sndPath2;

AVAudioPlayer *av3;
NSString *sndPath3;

- (void) soundPlay:(NSString *)audioName{
    if (av.playing) {
        [av stop];
    }
	sndPath = [[NSBundle mainBundle] pathForResource:audioName ofType:nil];
	NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:sndPath];
    av = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
    [av play];
}

//계속 음악 재생(Loop)
- (void) soundPlayLoop:(NSString *)audioName{
    if (av2.playing) {
        [av2 stop];
    }
	sndPath2 = [[NSBundle mainBundle] pathForResource:audioName ofType:nil];
	NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:sndPath2];
    av2 = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
    [av2 setNumberOfLoops:-1];//계속 음악 재생(Loop)
    av2.volume = 0.1;//안 먹는 듯....
    [av2 play];
}

//배경 음악 중지
- (void) soundPlayLoopStop {
    if (av2.playing) {
        [av2 stop];
    }
}

- (void) soundPlayAlarm:(NSString *)audioName{
    if (av3.playing) {
        [av3 stop];
    }
	sndPath3 = [[NSBundle mainBundle] pathForResource:audioName ofType:nil];
	NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:sndPath3];
    av3 = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
    [av3 play];
}

//SQLITE 관련 참조 문헌
//http://hayageek.com/ios-sqlite-tutorial-create-select/
//http://www.sqlite.org/c3ref/open.html
//http://www.sqlite.org/c3ref/exec.html
//리턴코드: 0:SQLITE_OK, 1: SQLITE_ERROR, 8, 9, 10:SQLITE_IOERR, 14,20, 100, 101 <== 정보문화사 책 페이지 373 참조


-(int) executeQuery:query
{
    

    NSLog(@"query = %@", query);
    
    
//    sqlite3* db = NULL;
//    sqlite3_stmt* stmt = NULL;
//    int rc=0;
//    rc = sqlite3_open_v2([filePath UTF8String], &db, SQLITE_OPEN_READONLY , NULL);
//    
    
    
    //sqlite3* db = NULL;


    const char *dbpath = [_databasePath UTF8String];
    int rc=sqlite3_open(dbpath, &_speedmatchDB); //DB 생성
    
    
    if (SQLITE_OK != rc) //DB 오픈에 문제가 있으면 ...
    {
        sqlite3_close(_speedmatchDB);
        NSLog(@"Failed to open db connection");
    } else { //DB 오픈에 문제가 없으면 ...
        NSLog(@"DB Open OK...");
        
        char * errMsg;
        rc = sqlite3_exec(_speedmatchDB, [query UTF8String] ,NULL, NULL, &errMsg);
        if(SQLITE_OK != rc) //쿼리 실행에 문제가 있으면 ...
        {
            NSLog(@"Failed to execute query  rc:%d, msg=%s", rc, errMsg);
        } else {
            NSLog(@"DB execute OK - query: %@", query);
        }
        sqlite3_close(_speedmatchDB);
    }
    return rc;
}



-(NSArray *) getRecords:(NSString*) filePath where:(NSString *)whereStmt
{
    NSMutableArray * students =[[NSMutableArray alloc] init];
    sqlite3* db = NULL;
    sqlite3_stmt* stmt = NULL;
    int rc=0;
    rc = sqlite3_open_v2([filePath UTF8String], &db, SQLITE_OPEN_READONLY , NULL);
    if (SQLITE_OK != rc)
    {
        sqlite3_close(db);
        NSLog(@"Failed to open db connection");
    }
    else
    {
        NSString  * query = @"SELECT * from students";
        if(whereStmt)
        {
            query = [query stringByAppendingFormat:@" WHERE %@",whereStmt];
        }
        
        rc =sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, NULL);
        if(rc == SQLITE_OK)
        {
            while (sqlite3_step(stmt) == SQLITE_ROW) //get each row in loop
            {
                
                NSString * name =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
                NSInteger age =  sqlite3_column_int(stmt, 2);
                NSInteger marks =  sqlite3_column_int(stmt, 3);
                
                NSDictionary *student =[NSDictionary dictionaryWithObjectsAndKeys:name,@"name",
                                        [NSNumber numberWithInteger:age],@"age",[NSNumber numberWithInteger:marks], @"marks",nil];
                
                [students addObject:student];
                NSLog(@"name: %@, age=%ld , marks =%ld",name,(long)age,(long)marks);
                
            }
            NSLog(@"Done");
            sqlite3_finalize(stmt);
        }
        else
        {
            NSLog(@"Failed to prepare statement with rc:%d",rc);
        }
        sqlite3_close(db);
    }
    
    return students;
    
}

//Call this Function at didFinishLaunchingWithOptions:
//resource 폴더에 있는 DB는 read-only로 밖에 사용할 수 없다.
//읽고 쓰기가 가능한 db를 사용하기 위해서는 도큐먼트 폴더에 db 를 복사해 두어야 한다.
-(void)createdb{
    /******************************************************
     * Database(contacts.db) 파일과 Table이 없으면 생성 (start)
     ******************************************************/
    NSString *docsDir;
    NSArray *dirPaths;
    
    // Get the documents directory
    // 읽고/쓰기 가능한 '도큐먼트' 디렉토리는 NSDocumentationDirectory가 아니고 NSDocumentDirectory임을 유의!!!
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = dirPaths[0];

    // Build the path to the database file
    _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"speedmatch.db"]];
    
    NSFileManager *filemgr = [NSFileManager defaultManager];
    
    if ([filemgr fileExistsAtPath:_databasePath] == NO) {
        const char *dbpath = [_databasePath UTF8String];
        
        int ret=sqlite3_open(dbpath, &_speedmatchDB); //DB 생성
        
        if (ret == SQLITE_OK) {
            char *errMsg;
            
            /*********************
             * 1. score 테이블 생성
             *********************/
            const char *sql_stmt = "CREATE TABLE score (no INTEGER PRIMARY KEY  NOT NULL ,highscore INTEGER DEFAULT (null) ,highstar VARCHAR DEFAULT (null))";
            if (sqlite3_exec(_speedmatchDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) { //테이블 생성
                NSLog(@"Failed to create SCORE table: %s", errMsg);
            } else {
                NSLog(@"score 테이블 생성 성공");
            }
            
            /**********************************************
             * 1-1. insert stage to score 테이블 (초기값 세팅)
             **********************************************/
            char* errorMessage;
            //char buffer[300];
            
            sqlite3_exec(_speedmatchDB, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);
            
            char buffer[] = "INSERT INTO score (no) VALUES (?)";
            sqlite3_stmt* stmt;
            sqlite3_prepare_v2(_speedmatchDB, buffer, (int)strlen(buffer), &stmt, NULL);
            
            for (unsigned i = 0; i < [_stages count]; i++)
            {
                sqlite3_bind_int(stmt, 1, i);

                if (sqlite3_step(stmt) != SQLITE_DONE)
                {
                    NSLog(@"%d's data Insert Failed!",i);
                } else {
                    NSLog(@"%d's data Insert OK",i);
                }
                
                sqlite3_reset(stmt);
            }
            
            sqlite3_exec(_speedmatchDB, "COMMIT TRANSACTION", NULL, NULL, &errorMessage);
            sqlite3_finalize(stmt);
            
            
            
            /*********************
             * 2. info 테이블 생성
             *********************/
            const char *sql_stmt2 = "CREATE TABLE info (key_name VARCHAR PRIMARY KEY NOT NULL, value VARCHAR DEFAULT (null))";
            if (sqlite3_exec(_speedmatchDB, sql_stmt2, NULL, NULL, &errMsg) != SQLITE_OK) { //테이블 생성
                NSLog(@"Failed to create INFO table: %s", errMsg);
            } else {
                NSLog(@"info 테이블 생성 성공");
            }
            
            
            /**********************************************
             * 2-1. insert to info 테이블 (초기값 세팅)
             **********************************************/
            
            sqlite3_stmt    *statement;
            const char *dbpath = [_databasePath UTF8String];
            
            if (sqlite3_open(dbpath, &_speedmatchDB) == SQLITE_OK)
            {
                
                NSString *insertSQL = [NSString stringWithFormat:
                                       @"insert into info values ('%@',%d)",
                                       @"HighWaterMark", 1];
                
                NSLog(@"insertSQL : %@", insertSQL);
                
                const char *insert_stmt = [insertSQL UTF8String];
                sqlite3_prepare_v2(_speedmatchDB, insert_stmt,
                                   -1, &statement, NULL);
                if (sqlite3_step(statement) == SQLITE_DONE)
                {
                    NSLog(@"Success to insert to info");
                } else {
                    NSLog(@"Failed to insert to info");
                }
                sqlite3_finalize(statement);
                sqlite3_close(_speedmatchDB);
            } else {
                NSLog(@"DB open failed ....");
            }
            

            
            
            
            sqlite3_close(_speedmatchDB);
            
            NSLog(@"Maybe..... 데이터베이스 생성 성공");
        } else {
            NSLog(@"Failed to open/create database");
            NSLog(@"Error Code: %d, message '%s'", ret, sqlite3_errmsg(_speedmatchDB));
            
        }
    } else {
        NSLog(@"데이터베이스 파일이 이미 존재하므로 기존 파일을 이용함...");
    }
    
    
    /*****************************************
     * Database 파일과 Table이 없으면 생성 (end)
     *****************************************/
}


//DB 읽어서 이전 결과를 초기값으로 반영
-(void)readdb{
    sqlite3* db = NULL;
    sqlite3_stmt* stmt = NULL;
    
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * docsDir = [paths objectAtIndex:0];
    NSString * theDBPath = [docsDir stringByAppendingPathComponent:@"speedmatch.db"];
    
    NSLog(@"theDBPath1 = %@", theDBPath);
    
    int rc=0;
    rc = sqlite3_open_v2([theDBPath UTF8String], &db, SQLITE_OPEN_READONLY , NULL);
    
    
    if (SQLITE_OK != rc)
    {
        sqlite3_close(db);
        NSLog(@"Failed to open db connection");
    }
    else
    {
        NSLog(@"Success to open db connection");
        
        /***********************************
         * 1. score 테이블 읽기
         ***********************************/
        NSLog(@"score 테이블 read...");
        
        
        NSString  * query = @"SELECT * from score";
        
        rc =sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, NULL);
        
        if(rc == SQLITE_OK)
        {
            NSLog(@"prepare ok");
            if (stmt == NULL) {
                NSLog(@"stmt is NULL");
            } else {
                NSLog(@"stmt is Not NULL");
            }
            
            while (sqlite3_step(stmt) == SQLITE_ROW) //get each row in loop
            {
                NSLog(@"in while");
                int stage_no = sqlite3_column_int(stmt, 0);
                int highscore = sqlite3_column_int(stmt, 1);
                NSString * highstar=@"";
                if (sqlite3_column_text(stmt, 2) != nil) {
                    highstar = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 2)];
                }
                
                [_highScores setObject:[NSNumber numberWithInt:highscore] forKey:[NSNumber numberWithInt:stage_no]];
                [_highStars setObject:highstar forKey:[NSNumber numberWithInt:stage_no]];
                
                //                NSDictionary *student =[NSDictionary dictionaryWithObjectsAndKeys:name,@"name",
                //                                        [NSNumber numberWithInteger:age],@"age",[NSNumber numberWithInteger:marks], @"marks",nil];
                //
                //                [students addObject:student];
                NSLog(@"stage_no: %d, highscore=%d, highstar=%@",(int)stage_no,(int)highscore,highstar);
                
            }
            NSLog(@"Done");
            sqlite3_finalize(stmt);
        }
        else
        {
            NSLog(@"Failed to prepare statement with rc:%d",rc);
        }
        
        
        
        
        /***********************************
         * 2. info 테이블 읽기
         ***********************************/
        
        NSLog(@"info 테이블 read...");
        
        query = @"SELECT key_name, value from info";
        
        rc =sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, NULL);
        
        if(rc == SQLITE_OK)
        {
            NSLog(@"prepare ok");
            if (stmt == NULL) {
                NSLog(@"stmt is NULL");
            } else {
                NSLog(@"stmt is Not NULL");
            }
            
            while (sqlite3_step(stmt) == SQLITE_ROW) //get each row in loop
            {
                NSLog(@"in while2");
                NSString * key_name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 0)];
                int value = sqlite3_column_int(stmt, 1);

                
                [_info setObject:[NSNumber numberWithInt:value] forKey:key_name];

                NSLog(@"from INFO table to dictionary INFO: key_name: %@, value=%d",key_name,(int)value);
                
            }
            NSLog(@"Done");
            sqlite3_finalize(stmt);
        }
        else
        {
            NSLog(@"Failed to prepare statement with rc:%d",rc);
        }
        
        
        
        sqlite3_close(db);
    }
    
    
    //_info dictionary 에서 읽어 highWaterMark에서 setting...
    _highWaterMark = [[_info objectForKey:@"HighWaterMark"] intValue]; ////
    
    NSLog(@"_highWaterMark(before) = %d",_highWaterMark);
    if (_highWaterMark == 0) {
        _highWaterMark = 1;
    }
    NSLog(@"_highWaterMark(after) = %d",_highWaterMark);
    
    
    NSLog(@"stages count = %lu", (unsigned long)[_stages count]); //stages count = 18 : 위의 [self fillData]에서 채움!
    
    //    for (int i=1; i<[stages count]+1; i++) {
    //        [highScores setObject:[NSNumber numberWithInt:0] forKey:[NSNumber numberWithInt:i]];
    //    }

}




-(void)saveHighWaterMarkToDB{
    sqlite3_stmt    *statement;
    const char *dbpath = [_databasePath UTF8String];
    
    if (sqlite3_open(dbpath, &_speedmatchDB) == SQLITE_OK)
    {
        
        NSString *updateSQL = [NSString stringWithFormat:
                               @"update info set value = %d where key_name = 'HighWaterMark'",
                               _highWaterMark];
        
        NSLog(@"insertSQL = %@", updateSQL);
        
        const char *update_stmt = [updateSQL UTF8String];
        sqlite3_prepare_v2(_speedmatchDB, update_stmt,
                           -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            NSLog(@"Success to save highWaterMark");
        } else {
            NSLog(@"Failed to save highWaterMark");
        }
        sqlite3_finalize(statement);
        sqlite3_close(_speedmatchDB);
    } else {
        NSLog(@"DB open fail....");
    }
}



@end
